package com.pn.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.pn.entity.Auth;
import com.pn.mapper.AuthMapper;
import com.pn.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@CacheConfig(cacheNames = "com.pn.service.impl.AuthServiceImpl")
@Service
public class AuthServiceImpl implements AuthService {

    //注入AuthMapper
    @Autowired
    private AuthMapper authMapper;

    //注入Redis模板
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 根据用户id查询用户权限(菜单)树的业务方法
     */
    @Override
    public List<Auth> findAuthTreeByUid(Integer userId) {
        //查询redis是否有该用户id的菜单树缓存
        String authTreeJson = redisTemplate.opsForValue().get("authTree:" + userId);
        if (StringUtils.hasText(authTreeJson)){
            List<Auth> authTreeList = JSON.parseArray(authTreeJson,Auth.class);
            return authTreeList;
        }
        //执行到这里说明没有缓存
        List<Auth> allAuthList = authMapper.findAllAuthByUid(userId);
        List<Auth> authTreeList = allAuthToAuthTree(allAuthList,0);
        //把菜单树存储到redis中
        authTreeJson = JSON.toJSONString(authTreeList);
        redisTemplate.opsForValue().set("authTree:" + userId,authTreeJson);
        return authTreeList;
    }
    @Cacheable(value = "auth:tree")
    @Override
    public List<Auth> findAuthTree() {
        List<Auth> allAuth = authMapper.findAllAuth();
        List<Auth> authTree = allAuthToAuthTree(allAuth, 0);
        return authTree;
    }

    private List<Auth> allAuthToAuthTree(List<Auth> allAuthList, Integer pid) {
        //查询pid是0的一级菜单
        List<Auth> firstLevelAuth = new ArrayList<>();
        for (Auth auth : allAuthList) {
            if (auth.getParentId() == pid){
                firstLevelAuth.add(auth);
            }
        }
        //递归调用查询二级菜单
        for (Auth auth : firstLevelAuth) {
            List<Auth> secondLevelAuth = allAuthToAuthTree(allAuthList, auth.getAuthId());
            auth.setChildAuth(secondLevelAuth);
        }
        return firstLevelAuth;
    }



}
